<script setup lang="ts">
// import { accountList } from '@/api/interface/web/account'
import { typeSelectTypeWithAccounts } from '@/api/interface/web/type'
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useUserStore } from '@/stores/user'
import BuyForm from '@/components/form/BuyForm.vue'
import { orderAdd, orderLists } from '@/api/interface/web/order'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()

const fullscreenLoading = ref(false)

const userStore = useUserStore()

const actTitle = ref('现成账号')

const actTitleFun = (text: any) => {
  actTitle.value = text
}

const typeOptions: any = ref([])

const getTypeOptions = () => {
  typeSelectTypeWithAccounts({})
    .then((res: any) => {
      typeOptions.value = res.map((v: any) => {
        return {
          ...v,
          ...v.accounts[0],
          num: 1,
          active: false,
        }
      })

      console.log(typeOptions.value.map((v: any) => v.name).join(','))
    })
    .finally(() => {
      fullscreenLoading.value = false
    })
}
getTypeOptions()

const buyAccount = (row: any) => {
  if (!userStore.userInfo) {
    goLogin()
  } else {
    dialogBuyVisible.value = true
    const { name, price, id, avatar } = row
    buyData.value = {
      name: name,
      num: 1,
      price: price,
      accountId: id,
      typeName: name,
      avatar: avatar,
    }
  }
}

//工单
const goWorkOrder = () => {
  if (!userStore.userInfo) {
    goLogin()
  } else {
    router.push({ path: '/work' })
  }
}

// 去登录
const goLogin = () => {
  ElMessageBox.confirm('需要登录才能进行购买,否则去登录?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      userStore.setDialogLoginVisible(true)
    })
    .catch(() => {})
}

const buyData = ref()
const buyFormRef = ref()
const dialogBuyVisible = ref(false)

const handleDialogBuyClose = () => {
  dialogBuyVisible.value = false
}

const handleDialogBuySubmit = () => {
  fullscreenLoading.value = true
  buyFormRef.value.submitForm().then((data: any) => {
    if (data) {
      if (userStore.userInfo.money < parseFloat(data.num) * parseFloat(data.price)) {
        fullscreenLoading.value = false
        ElMessageBox.confirm('余额不足,是否充值?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            router.push({ path: '/score' })
          })
          .catch(() => {})
      } else {
        orderAdd(data)
          .then((data: any) => {
            if (data) {
              dialogBuyVisible.value = false
              ElMessage.success('购买成功!')
              userStore.refreshUserInfo()
              getOrdersFun()
            }
          })
          .finally(() => {
            fullscreenLoading.value = false
          })
      }
    }
  })
}

const orderPage: any = ref(1)
const orderSize: any = ref(10)
const orderTotal: any = ref(10)
const orders: any = ref([])
const getOrdersFun = () => {
  if (!userStore.userInfo) {
    orders.value = []
    return
  }
  const userId = userStore.userInfo.id
  orderLists({ userId, page: orderPage.value, size: orderSize.value }).then((res: any) => {
    orders.value = res.list.map((v: any) => {
      return {
        ...v,
      }
    })

    orderTotal.value = res.total
  })
}
const handleCurrentChange = () => {
  getOrdersFun()
}

let intervalGetOrders: any = null
watch(
  orders,
  () => {
    const hasNeedSendOrders: any = orders.value.filter((v: any) => v.status == '1')
    if (hasNeedSendOrders.length) {
      clearIntervalFun()
      intervalGetOrders = setInterval(function () {
        getOrdersFun()
      }, 12000)
    } else {
      clearIntervalFun()
    }
  },
  {
    deep: true,
  },
)
const clearIntervalFun = () => {
  if (intervalGetOrders) {
    clearInterval(intervalGetOrders)
    intervalGetOrders = null
  }
}

const download = (item: any) => {
  const blob = new Blob([item.remark], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `${item.name}---${item.price}元.txt`

  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
}

const getRefreshOrdersFun = () => {
  ElMessage.success('刷新成功!')
  getOrdersFun()
}

//获取已发货的订单
const sendedOrderLists: any = ref([])
const getSendedOrderLists = () => {
  orderLists({ status: '2', page: 1, size: 10 }).then((res: any) => {
    sendedOrderLists.value = res.list.map((v: any) => {
      return {
        ...v,
        username: v.username && v.username.length > 5 ? v.username.slice(0, 5) + '...' : v.username,
      }
    })

    sendedOrderLists.value = [...sendedOrderLists.value, ...sendedOrderLists.value]
  })
}

const scollStyle: any = computed(() => {
  return `animation: verticalScroll ${sendedOrderLists.value.length}s linear infinite`
})

onMounted(() => {
  if (userStore.userInfo) {
    userStore.refreshUserInfo()
  }
  getOrdersFun()
  getSendedOrderLists()
})

onUnmounted(() => {
  clearIntervalFun()
})

watch(
  () => userStore.userInfo,
  () => {
    getOrdersFun()
  },
)
</script>

<template>
  <div class="home-wrapper" v-loading.fullscreen="fullscreenLoading">
    <div class="account-wrapper">
      <div class="title-box">
        <h1
          :class="{ title: true, active: actTitle == '现成账号' }"
          @click="actTitleFun('现成账号')"
        >
          现成独立账号
        </h1>
      </div>
      <p class="description">
        <span style="word-wrap: break-word"
          >欢迎来到激活页面，购买<strong>独立成品号</strong>。<strong
            >工作时间:10:00-19:00 15分钟内发货。</strong
          >
        </span>
        <el-button @click="goWorkOrder">申请工单</el-button>
      </p>

      <div class="home-content">
        <div class="account-box">
          <div class="account-item" v-for="(item, index) in typeOptions" :key="index">
            <div class="icon-name-number-price">
              <img class="icon" :src="'/images/icon' + item.avatar" alt="" />
              <div class="name">{{ item.name }}</div>
              <div class="number">可用的: {{ item.total }}个</div>
              <div class="price">价格: {{ item.price }}元</div>
            </div>
            <div class="buy" @click="buyAccount(item)">买</div>
          </div>
        </div>
      </div>
    </div>

    <div class="order-wrapper">
      <div class="title-box">
        <h1
          :class="{ title: true, active: actTitle == '现成账号' }"
          @click="actTitleFun('现成账号')"
        >
          激活列表
        </h1>

        <div class="refresh-btn" @click="getRefreshOrdersFun">
          <el-icon><Refresh /></el-icon>
          <span class="text">刷新</span>
        </div>
      </div>
      <div class="order-box">
        <div class="order-content" v-if="orders.length > 0">
          <div class="order-item" v-for="(item, index) in orders" :key="index">
            <div class="avatar-name-price">
              <div class="avatar-name">
                <img class="avatar" :src="'/images/icon' + item.avatar" alt="" />
                <div class="name">{{ item.name }}</div>
              </div>
              <div class="price-num-sum">{{ item.price }} x {{ item.num }} = {{ item.sum }}元</div>
            </div>

            <div class="status-utils">
              <div class="status">
                <span class="success" v-if="item.status == 2">已发货</span>
                <span class="info" v-if="item.status == 1">未发货</span>
              </div>

              <div class="utils" v-if="item.status == 2">
                <el-button type="primary" class="download" link @click="download(item)">
                  下载
                </el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="order-content no-data" v-else>暂无激活数据</div>
        <el-pagination
          size="small"
          background
          v-model:current-page="orderPage"
          :page-size="10"
          layout="total, prev, pager, next"
          :total="orderTotal"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <div class="buy-history-box">
      <div class="history-title">发货历史</div>
      <div class="history-item-box">
        <div class="history-item-scroll" :style="scollStyle">
          <div
            class="history-item"
            v-for="(item, index) in sendedOrderLists"
            :key="'first' + index"
          >
            {{ item.username }}下单{{ item.num }}个{{ item.name }}已发货
          </div>
        </div>
      </div>
    </div>
  </div>

  <BaseDialog v-model="dialogBuyVisible" width="420px">
    <template #title> 购买---15分钟内发货 </template>
    <template #buttons>
      <el-button type="info" text bg @click="handleDialogBuyClose">取消</el-button>
      <el-button type="primary" @click="handleDialogBuySubmit" class="buyConfirm"
        >确认购买</el-button
      >
    </template>
    <BuyForm ref="buyFormRef" :data="buyData" />
  </BaseDialog>
</template>
<style lang="scss" scoped>
.home-wrapper {
  width: 1200px;
  height: 100%;
  display: flex;
  position: relative;

  .account-wrapper {
    width: 820px;
    padding: 20px 20px;
    margin-right: 30px;
    height: 100%;
    box-sizing: border-box;
    border: 1px solid #e1e6ee;
    border-radius: 8px;
    background: #fff;
    color: #3a5072;
    display: flex;
    flex-direction: column;

    .title-box {
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      .title {
        font-weight: 500;
        font-size: 18px;
        color: #a9a9a9;
        margin-bottom: 10px;
      }

      .title.active {
        font-weight: 700;
        color: #333;
      }

      .icon {
        font-weight: 700;
        font-size: 30px;
        padding: 0 5px;
        margin-top: -5px;
      }
    }

    .description {
      color: #4c4c4c;
      font-size: 14px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .home-content {
      border: 1px solid #e1e6ee;
      border-radius: 16px;
      margin-top: 20px;
      flex: 1;
      border-radius: 8px;
      width: 100%;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      overflow-y: hidden;

      .title {
        color: #ea5400;
        font-size: 20px;
        font-weight: 700;
        margin-bottom: 20px;
      }

      .account-box {
        flex: 1;
        overflow-y: auto;

        .account-item {
          border-bottom: 1px solid #e1e6ee;
          padding: 12px 20px;
          padding-left: 3px;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .icon-name-number-price {
            display: flex;
            align-items: center;

            .icon {
              width: 60px;
            }

            .name {
              width: 200px;
              color: #333;
              font-weight: 700;
              font-size: 14px;
            }

            .number {
              width: 180px;
              color: #4c4c4c;
              font-weight: 400;
              font-size: 14px;
            }

            .price {
              width: 180px;
              color: #4c4c4c;
              font-weight: 400;
              font-size: 14px;
            }
          }

          .buy {
            cursor: pointer;
            background: linear-gradient(83.15deg, #f67a01 3.74%, #eb5701 103.11%);
            border-radius: 5px;
            color: #fff;
            font-weight: 700;
            font-size: 13px;
            padding: 8px 24px;
          }
        }

        .account-item:last-child {
          border-bottom: 0;
        }
      }
    }
  }

  .order-wrapper {
    width: 350px;
    padding: 20px 20px;
    height: 100%;
    overflow-y: auto;
    box-sizing: border-box;
    border: 1px solid #e1e6ee;
    border-radius: 8px;
    background: #fff;
    color: #3a5072;
    display: flex;
    flex-direction: column;

    .title-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 18px;

      .title {
        font-weight: 500;
        font-size: 18px;
        font-weight: 700;
        color: #333;
      }
      .refresh-btn {
        display: flex;
        align-items: center;
        cursor: pointer;

        .text {
          margin-left: 5px;
        }
      }
    }

    .order-box {
      flex: 1;
      overflow: hidden;
      display: flex;
      flex-direction: column;

      .order-content {
        border: 1px solid #e1e6ee;
        border-radius: 8px;
        flex: 1;
        overflow-y: auto;
        margin-bottom: 15px;
        .order-item {
          width: 100%;
          padding: 16px;
          box-sizing: border-box;
          border-bottom: 1px solid #e1e6ee;

          .avatar-name-price {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-left: -17px;
            margin-bottom: 8px;

            .avatar-name {
              display: flex;
              align-items: center;
              .avatar {
                width: 60px;
              }
              .name {
                color: #333;
                font-weight: 700;
                font-size: 14px;
              }
            }

            .price-num-sum {
              font-size: 14px;
              align-items: center;
              justify-content: space-between;
            }
          }

          .status-utils {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .status {
              .success {
                font-size: 14px;
                color: var(--theme-color-success);
              }

              .info {
                font-size: 14px;
                color: var(--theme-color-info);
              }
            }
          }

          .utils {
            .download {
              padding: 0;
            }
          }
        }

        // .order-item:nth-child(odd) {
        //   background-color: #f0f5ff;
        // }

        .order-item:last-child {
          border-bottom: 0;
        }
      }

      .order-content.no-data {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      :deep(.el-pagination.is-background) {
        --el-pagination-hover-color: var(--theme-color);
        .el-pager {
          li.is-active {
            background-color: var(--theme-color);
          }
        }
      }
    }
  }

  .buy-history-box {
    width: 250px;
    border: 1px solid #e1e6ee;
    border-radius: 8px;
    position: absolute;
    left: -280px;
    box-sizing: border-box;

    .history-title {
      font-size: 15px;
      font-weight: bold;
      padding: 10px;
      border-bottom: 1px solid #e1e6ee;
    }

    .history-item-box {
      height: 300px;
      padding: 0 10px;
      overflow-y: hidden;

      .history-item {
        height: 30px;
        line-height: 30px;
        font-size: 14px;
      }
    }
  }
}
</style>
<style lang="scss">
.buyConfirm {
  background-color: var(--theme-color);
  border: 0;
}

.buyConfirm:hover {
  background-color: #e7712e;
}

/* 上下滚动动画 */
@keyframes verticalScroll {
  0% {
    transform: translateY(0);
  }
  100% {
    transform: translateY(-50%);
  }
}
</style>
